<?php


class incident_overview
{
	var $data= Array();
	var $items = Array();
	var $valid = false;

	function incident_overview()
	{
		global $lang, $db, $properties;
		
		if(isset($_POST['submitIncident']))
		{
			$this->addIncident();
		}
		
		include_once('includes/addMessage.php');
		$this->items[] = new addMessage('', $lang['UserCPMyIncidents']);
		
		$q = 'SELECT e_title, d_title, c_title, c_smallTitle, t_fullTitle, date_format(ed_date, "%M %e, %Y") as ed_dateF, 
					 in_id, id_role, in_race, in_lap, in_corner, in_adminstatus
			  FROM ' . EVENTS_TABLE . ', ' . EVENTDATES_TABLE . ', ' . DIVISIONS_TABLE . ', ' . CHAMPIONSHIPS_TABLE . 
			  	   ', ' . TRACKS_TABLE . ', ' . INCIDENTS_TABLE .  '
			  LEFT JOIN ' . INCIDENTDRIVERS_TABLE . ' ON (id_incident = in_id AND id_driver = ' . $_SESSION['valid_id'] . ')
			  WHERE e_id = ed_event and e_championship = c_id and d_id = ed_division and d_champid = c_id
      				and e_track = t_id and e_id = in_event and d_id = in_division 
					and (in_reportee = ' . $_SESSION['valid_id'] . ' OR NOT ISNULL(id_role))
			  GROUP BY in_id
			  ORDER BY ed_date DESC, e_id ASC, d_order ASC, in_race ASC, in_lap ASC';
		
		$res = $db->sql_query($q);
		while ($row = $db->sql_fetchrow($res))
		{
			$this->data[] = $row;
		}
	}
	
	function addIncident()
	{
		global $lang;
		
		$valid = true;
		
		if(!isset($_SESSION['incident']) || count($_SESSION['incident']) == 0)
		{
			$valid = false;
			echo '1';
		}
		else if(!isset($_POST['lap']) || ! is_numeric($_POST['lap']))
		{
			$valid = false;
			echo '2';
		}
		else if(!isset($_POST['replaytime']) || trim($_POST['replaytime']) == '' || trim($_POST['replaytime']) == 'hh:mm:ss')
		{
			$valid = false;
			echo '3';
		}
		else if(!isset($_POST['corner']) || trim($_POST['corner']) == '')
		{
			$valid = false;
			echo '4';
		}
		else if(!isset($_POST['explanation']) || trim($_POST['explanation']) == '')
		{
			$valid = false;
			echo '5';
		}
		else if(!isset($_POST['event']) || trim($_POST['event']) == '')
		{
			$valid = false;
			echo '6';
		}
		else if(!isset($_POST['division']) || trim($_POST['division']) == '')
		{
			$valid = false;
			echo '7';
		}
		else if(!isset($_POST['race']) || trim($_POST['race']) == '')
		{
			$valid = false;
			echo '8';
		}
			include_once('includes/addMessage.php');
		
		if(! $valid)
		{
			$this->items[] = new addMessage($lang['InicidentAddDataError'], $lang['IncidentAdd']);
		}
		else
		{
			global $db, $properties, $www_path;
			
			$qUpd = "insert into  ". INCIDENTS_TABLE . " (in_reportee, in_event, in_division, in_race, in_lap, " 
							. "in_replaytime, in_corner, in_explanation, in_adminstatus, in_raisedtime) values(" .
								 $_SESSION['valid_id'] . ", " . 
								 $_POST['event'] . ", " . 
								 $_POST['division']  . ', ' . 
								 $_POST['race'] . ', ' . 
								 $_POST['lap'] . ', "' . 
								 $_POST['replaytime']. '", "' . 
								 $_POST['corner']. '", "' . 
								 $_POST['explanation']. '", 0, NOW())';

			$db->sql_query("LOCK TABLES ". INCIDENTS_TABLE . "  WRITE");
			$db->sql_query("SET AUTOCOMMIT = 0");
			$db->sql_query($qUpd);
			$insertID = $db->sql_nextid();
			$db->sql_query("COMMIT");
			$db->sql_query("SET AUTOCOMMIT = 1");
			$db->sql_query("UNLOCK TABLES");
			
			$involvedDrivers = $_SESSION['incident'];
			
			if($insertID  > 0)
			{
				foreach($involvedDrivers as $driverID => $driverDetails)
				{
					/*echo $driverDetails['name'] . ' (' . ($driverDetails['role'] == 0 ? $lang['IncidentAtFault'] : $lang['IncidentVictim']) . ') ' . 
					'<a href="#" onClick="getRemoveDriver(' . $driverID . ')">' . $lang['RemoveButton'] . '</a>' .
					'<br>';*/
					$qUpd = 'INSERT INTO ' . INCIDENTDRIVERS_TABLE . ' (id_incident, id_driver, id_role) values(' .
								$insertID . ', ' . $driverID . ', ' . $driverDetails['role'] . ')';
					$db->sql_query($qUpd);
				}
				
				unset($_SESSION['incident']);
				$this->items[] = new addMessage($lang['InicidentAddSuccess'], $lang['IncidentAdd']);
				
				include_once('includes/email.php');

				$q = 'SELECT d.user_id, pf_drivername, u.user_email 
					  FROM ' . DRIVERNAME_TABLE . ' d, ' . USERS_TABLE . ' u, ' . INCIDENTDRIVERS_TABLE . '
					  WHERE u.user_id = d.user_id AND u.user_id = id_driver AND id_incident = ' . $insertID;
				$res = $db->sql_query($q);
				while ($row = $db->sql_fetchrow($res))
				{
					//dont send an email to yourself.
					if($row['user_id'] != $_SESSION['valid_id'])
					{
						$email = new email('incident_created', $row);
						$email->addReplacement('{INCIDENT_ID}' , $insertID);
						$email->addReplacement('{EMAILADRESS}' , 'user_email', 1);
						$email->addReplacement('{DRIVERNAME}' , 'pf_drivername', 1);
						$email->addReplacement('{COMMENT_TIME}' , $properties['event_incident_reply']);
						$email->addReplacement('{INCIDENTLINK}' , '<a href="' . $www_path . 'usercp.php?action=viewincident&id=' . $insertID . '">' . 
																 $www_path . 'usercp.php?action=viewincident&id=' . $insertID . '</a>' );
						$email->sendEmail();
					}
				}
			}
			else
			{
				$this->items[] = new addMessage($lang['InicidentAddDataError'], $lang['IncidentAdd']);
				echo '9';
			}
		}
		
	}
	
	function render()
	{
		foreach($this->items as $value)
		{
			$value->render();
		}
		
		global $lang, $skin_dir;
		
		$count = 0;
		$lastevent = '';
		
		foreach($this->data as $incident)
		{
			if($count == 0)
			{
				include $skin_dir . 'tpl/tableStart.tpl';	
				include $skin_dir . 'tpl/incidentListHeader.tpl';	
			}
			$count++;
			
			if($lastevent == $incident['d_title'] . ':' . $incident['e_title'])
			{
				$incident['remStart'] = '<!--';
				$incident['remEnd'] = '-->';
			}
			else
			{
				$incident['remStart'] = '';
				$incident['remEnd'] = '';
			}
			
			$lastevent = $incident['d_title'] . ':' . $incident['e_title'];
			
			$incident['title'] = $incident['c_title'] == $incident['d_title'] ? $incident['c_title'] : $incident['c_smallTitle'] . ' ' . $incident['d_title'];
			$incident['title'] .= ' ' . $incident['e_title'] . ', ' . $incident['t_fullTitle'] . ', ' . $incident['ed_dateF'];
			
			$incident['details'] = $lang['ResultsRace'] . ' ' . $incident['in_race'] . ', ' . $lang['IncidentLap'] . ' ' . 
										$incident['in_lap'] . ', ' . $lang['IncidentCorner'] . ': ' . $incident['in_corner'];
			
			if(is_null($incident['id_role']))
			{
				$incident['myinvolvement'] = $lang['IncidentReportee'];
			}
			else if($incident['id_role'] == 0)
			{
				$incident['myinvolvement'] = $lang['IncidentAtFault'];
			}
			else
			{
				$incident['myinvolvement'] = $lang['IncidentVictim'];
			}
			
			$incident['casestatus'] = $lang['IncidentStatus'][$incident['in_adminstatus']];
			$incident['link'] = '<a href="usercp.php?action=viewincident&id=' . $incident['in_id'] . '">' . $lang['ViewButton'] . '</a>';
			
			include $skin_dir . 'tpl/incidentListItem.tpl';
			
		}
		
		if($count > 0)
		{
			include $skin_dir . 'tpl/tableEnd.tpl';	
		}
	}
}

class incident_detail
{
	var $data;
	var $items = Array();
	var $drivers = Array();
	var $valid = false;

	function incident_detail($id)
	{
		global $lang, $db, $properties;
				
		include_once('includes/addMessage.php');
		
		$q = 'SELECT e_title, d_title, c_id, e_id, c_title, c_smallTitle, t_fullTitle, date_format(ed_date, "%M %e, %Y") as ed_dateF, 
					 in_id, in_race, in_lap, in_corner, in_adminstatus, in_explanation, in_replaytime, ar_verdict,
					 date_format(in_raisedtime, "%M %e, %Y, %l:%i%p") as in_raisedtime,
					 DATE_ADD(in_raisedtime, INTERVAL ' . $properties['event_incident_reply'] . ' HOUR) > NOW() as comments_allowed,
       				(DATE_ADD(ar_date, INTERVAL ' . $properties['event_incident_appeal'] . ' HOUR) > NOW() AND ar_ptspen > 0 OR ar_weightpen > 0) as appeal_allowed
			  FROM ' . EVENTS_TABLE . ', ' . EVENTDATES_TABLE . ', ' . DIVISIONS_TABLE . ', ' . CHAMPIONSHIPS_TABLE . 
			  	   ', ' .  TRACKS_TABLE . ', ' . INCIDENTS_TABLE .  '
 			  LEFT JOIN ' . INCIDENTDRIVERS_TABLE . ' ON (id_incident = in_id AND id_driver = ' . $_SESSION['valid_id'] . ')
			  LEFT JOIN ' . INCIDENTADMINREVIEW_TABLE . ' ON (id_incident = ar_incident AND ar_driver = id_driver AND ar_admin = 0)
			  WHERE e_id = ed_event and e_championship = c_id and d_id = ed_division and d_champid = c_id and
       				e_track = t_id and e_id = in_event and d_id = in_division and in_id = ' . $id . '
					and (in_reportee = ' . $_SESSION['valid_id'] . ' OR NOT ISNULL(id_role))';

		$res = $db->sql_query($q);
		if ($row = $db->sql_fetchrow($res))
		{
			$this->data = $row;
			
			$this->items[] = new addMessage('', str_replace('{ID}', $id, $lang['IncidentTitle']));
			$this->items[] = $this;
						
			$qD = 'SELECT user_id, pf_drivername, ar_verdict, id_role, as_ruling, ar_explanation, 
						  ar_ptspen, ar_weightpen, date_format(ar_date, "%M %e, %Y") as ar_dateF
			  	   FROM ' . DRIVERNAME_TABLE . ', ' . INCIDENTDRIVERS_TABLE .  '
			  LEFT JOIN ' . INCIDENTADMINREVIEW_TABLE . ' ON (id_incident = ar_incident AND ar_driver = id_driver AND ar_admin = 0)
			  LEFT JOIN ' . INCIDENTADMINRULINGS_TABLE . ' ON (ar_verdict = as_id)
			  WHERE user_id = id_driver AND id_incident = ' . $row['in_id'] . '
			  ORDER BY pf_drivername ASC';

			$resD = $db->sql_query($qD);
			while ($driver = $db->sql_fetchrow($resD))
			{
				$this->drivers[] = $driver;
			}
						
			include_once 'includes/comments.php';
			
			//1 = incidents, $id = which incident comments to show, 1 = show comments directed to me or from me only
			$this->items[] = new listComments(1, $id, $lang['CommentTitle'], 1); 
			
			if($row['in_adminstatus'] == 0)
			{
				if(! $row['comments_allowed'])
				{
					$this->items[] = new addComment(1, $id, 'usercp.php?action=viewincident&id=' . $id, str_replace('{ID}', $id, $lang['IncidentCommentTitle']), 
													'', '', '<br>' . $lang['IncidentsAdminComments'] . '<br>' . $lang['IncidentsReplyPassed']); 
				}
				else
				{
					//1 = incidents, $id = which incident to add comment too, 'usercp... ' = which action to use (must show comments or call addComment on this page), default title for comment
					$this->items[] = new addComment(1, $id, 'usercp.php?action=viewincident&id=' . $id, str_replace('{ID}', $id, $lang['IncidentCommentTitle']), 
													'', '', '<br>' . $lang['IncidentsAdminComments']); 
				}
			}
			
			//1 = incidents, $id = which incident comments to show, 1 = show comments directed to me or from me only
			$commentList = new listComments(2, $id, $lang['IncidentsAppealCommentsTitle'], 1, true); 
			$this->items[] = $commentList;
			
			//have we added an appeal?
			if($commentList->commentAddedCatagory() == 2)
			{
				$q = 'UPDATE ' . INCIDENTS_TABLE . ' 
					  SET in_adminstatus = 2
					  WHERE in_adminstatus != 3 AND in_id = ' . $row['in_id'];
				$db->sql_query($q);
				if($db->sql_affectedrows() > 0)
				{
					$row['in_adminstatus'] = 2;
					$this->data['in_adminstatus'] = 2;
				}
			}
			
			
			//if we have had a verdict for this user
			if($row['ar_verdict'] > 0 && $row['in_adminstatus'] > 0 && $row['in_adminstatus'] < 3)
			{
				if($row['appeal_allowed'])
				{
					//1 = incidents, $id = which incident to add comment too, 'usercp... ' = which action to use (must show comments or call addComment on this page), default title for comment
					$this->items[] = new addComment(2, $id, 'usercp.php?action=viewincident&id=' . $id, str_replace('{ID}', $id, $lang['IncidentAppealTitle']), '', 
													$lang['IncidentsAppealAddCommentTitle'],$lang['IncidentsAppealAddCommentMessage'], '', '<br>' . $lang['IncidentsAdminComments']); 
				}
				else
				{
					$this->items[] = new addMessage($lang['IncidentsAppealPassed'], '');
				}
			}
		}
		else
		{
			$this->items[] = new addMessage($lang['ErrorInsufficientPermissions'], $lang['ErrorTitle']);
		}
		
	}
	
	
	function render()
	{
		foreach($this->items as $value)
		{
			if($value != $this)
			{
				$value->render();
			}
			else
			{
				global $lang, $skin_dir;
				
				$data = $this->data;
				$data['in_adminstatus'] = $lang['IncidentStatus'][$data['in_adminstatus']];
				$driversInfo = '';
				
				foreach($this->drivers as $driver)
				{
					if($driversInfo != '')
					{
						$driversInfo .= '<br><br>';
					}
				
					$driversInfo .= '<a href="drivers.php?id=' . $driver['user_id'] . '">' . $driver['pf_drivername'] . '</a> (' . $lang['IncidentFault'][$driver['id_role']] . ')';
					
					if(! is_null($driver['ar_verdict']))
					{
						$driversInfo .= ' - ' . $driver['ar_dateF'] . ': ' . $driver['as_ruling'] . '<br>' . $driver['ar_explanation'];
						
						if(! is_null($driver['ar_ptspen']) && $driver['ar_ptspen'] != 0)
						{
							$driversInfo .= '<BR>' . $lang['IncidentPointsPenalty'] . ' ' . $driver['ar_ptspen'] . $lang['ResultsPtsUnit'];
						}
						
						if(! is_null($driver['ar_weightpen']) && $driver['ar_weightpen'] != 0)
						{
							$driversInfo .= '<BR>' . $lang['IncidentWeightPenalty'] . ' ' . $driver['ar_weightpen'] . $lang['ResultsWeightUnit'];
						}
					}
				}
				$driversInfo = formatOutput($driversInfo);
				
				$data['championshipName'] = '<a href="championships.php?id=' . $data['c_id'] . '">' . 
											($data['d_title'] == $data['c_title'] ? $data['c_title'] : $data['c_title'] . ': ' . $data['d_title']) .
											'</a>';
				$data['eventName'] = '<a href="events.php?id=' . $data['e_id'] . '">' . 
									 ($data['e_title'] . ' ' . $data['t_fullTitle'] . ' ' . $lang['ResultsRace'] . ' ' . $data['in_race']) .
									 '</a>';
				$data['in_explanation'] = formatOutput($data['in_explanation']);
				
				
					
				include $skin_dir . 'tpl/incidentView.tpl';
				
			}
		}
		
	}
}

?>